const Koa = require('koa')
const app = new Koa()
const helmet = require('koa-helmet');
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const { error } = require('./config/error')
const bodyparser = require('koa-bodyparser')
const { koaBody } = require('koa-body');
const jwtKoa = require('koa-jwt')
const { verifyToken,JWT_SECRET,unlessPathList } = require('./config/jwt')
const logger = require('koa-logger')
const router = require('./routes')
const routerConfig = require('./routes/config')
const cors = require("@koa/cors")
const corsConfig = require("./config/cors")

app.use(cors(corsConfig))

// error handler
onerror(app, {
  accepts() {
    return 'json';
  },
  json: error
});

// 使用 Koa-helmet 中间件
app.use(helmet());

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(require("koa-static")(__dirname + "/public/apidoc"))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// 配置 koa-body 中间件，以便在请求中解析出文件上传数据
app.use(koaBody({
  multipart: true,
  formidable: {
    // 上传存放的路劲
    //uploadDir: path.join(__dirname,'./upload'),
    maxFieldsSize: 10 * 1024 * 1024, // 最大文件大小为 10MB
    multipart: true,
    keepExtensions: true, // 保持原始文件的扩展名
    onError(err){
      app.status = 400;
      // 这里可以定义自己的返回内容
      app.body = { code: 400, msg: "上传失败", data: {} };
      return;
   }
  }
}));

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

//token
app.use(verifyToken)
app.use(jwtKoa({secret:JWT_SECRET}).unless({path: unlessPathList}))

// routes
app.use(routerConfig());
app.use(router.routes(),router.allowedMethods())


// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
)

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
